const form = layui.form
//=============================== 获取列表数据 =============================
let params = {
    type: 1, //广告描述
    page: 1, // 广告名称
    limit: 5// 页数
}
async function rander(params) {
    const paramsdata = await axios.get('/ydd_link/list', { params })
    const { data, count } = paramsdata.data.data
    randerPage(count, params)
    randerTable(data, params)
}
rander(params)

//================================ 渲染表格 =============================
function randerTable(data, params) {
    layui.use('table', function () {
        const table = layui.table;
        console.log(params.type);
        //第一个实例
        table.render({
            elem: '#demo'
            , data: data
            , defaultToolbar: ``
            , cols: [
                params.type === 1 ?
                    [
                        { title: '序号', fixed: 'left', width: 80 }
                        , { field: 'title', title: '标题', }
                        , { field: 'des', title: '链接描述', }
                        , { title: '链接类型', toolbar: '#toolbarDemo3' }
                        , { field: 'url', title: '链接地址', }
                        , { title: '操作', toolbar: '#toolbarDemo2' }
                    ]
                    : [
                        { title: '序号', fixed: 'left', width: 80 }
                        , { field: 'des', title: '链接描述', }
                        , { title: '图片', toolbar: '#toolbarDemo1' }
                        , { title: '链接类型', toolbar: '#toolbarDemo3' }
                        , { field: 'url', title: '链接地址', }
                        , { title: '操作', toolbar: '#toolbarDemo2' }
                    ]
            ]
            , done: async function (res, curr, count) {
                qsa('tbody [data-field="0"] .layui-table-cell').forEach(function (ele, i) {
                    ele.innerHTML = i - 4
                })
                res.data.forEach((ele, i) => {
                    const { type } = ele
                    qsa('tbody [data-field="3"] .layui-table-cell .tip')[i].innerHTML = type === '1' ? '文字链接' : '图片链接'
                });
                params.type === 1 ? qsa('.tip').forEach(ele => {
                    ele.style.color = '#1E9FFF'
                    ele.style.background = '#1e9eff1d'
                }) : qsa('.tip').forEach(ele => {
                    ele.style.color = '#16b777'
                    ele.style.background = '#16b7771d'
                })
            }
        });
        //============================= 头部工具 ==============================
    })
}
function openList1(btnType) {
    layer.open({
        type: 1,
        area: '850px',
        resize: false,
        shadeClose: true,
        title: btnType === 'addItem' ? '新增链接' : '编辑链接',
        content:
            `<form class="layui-form" lay-filter="filter" id="addOrEdit">
                <div class="layui-form-item">
                    <label class="layui-form-label" lay-verify><i>*</i>链接类型</label>
                    <select name="type" lay-filter="test">
                        <option value="">请选择链接类型</option>
                        <option value="1">文字链接</option>
                        <option value="2">图片链接</option>
                    </select>
                </div>
                <div class="layui-form-item" id="title">
                    <label class="layui-form-label" lay-verify><i>*</i>标题</label>
                    <div class="layui-input-block">
                        <input type="text" name="title" placeholder="请输入标题" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label" lay-verify><i>*</i>链接地址</label>
                    <div class="layui-input-block">
                        <input type="text" name="url" placeholder="请输入链接地址" autocomplete="off" class="layui-input">
                    </div>
                </div>  
                <div class="layui-form-item">
                    <label class="layui-form-label" lay-verify><i>*</i>链接描述</label>
                    <div class="layui-input-block">
                        <textarea name="des" placeholder="请输入链接描述" class="layui-textarea"></textarea>
                    </div>
                </div>
                <div class="layui-form-item last" id="img">
                    <label class="layui-form-label" lay-verify><i>*</i>链接图片</label>
                    <div class="layui-input-block">
                        <input type="file" name="img" placeholder="请选择上传图片" autocomplete="off" style="display:none">
                        <div class="showPic">
                            <img src="" alt="" class="pic">
                            <p class="openLp">点击查看图片详情</p>
                            <label><i class="fa fa-check"></i></label>
                            <i class="fa fa-close close"></i>
                        </div>
                        <button type="button" class="layui-btn layui-btn-normal" id="upload">上传图片</button>
                    </div>
                </div>                
            </form>`,
        btn: ['提交', '重置'],
        btn1: async function (index) {
            const form = layui.form
            const type = qs('[name="type"]').value
            if (!qs('[name="type"]').value) return layer.msg('请选择链接种类', { time: 1000 })
            if (!qs('[name="url"]').value) return layer.msg('请输入链接地址', { time: 1000 })
            if (!qs('[name="des"]').value) return layer.msg('请输入链接描述', { time: 1000 })
            if (qs('[name="img"]').value === '' && type === '2') return layer.msg('请上传图片', { time: 1000 })
            if (qs('[name="title"]').value === '' && type === '1') return layer.msg('请填写标题', { time: 1000 })
            let formData = form.val('filter')
            formData.img.length === 0 ? formData.img = null : ''
            btnType === 'addItem' ? '' : formData.id = btnType
            await axios.post(
                btnType === 'addItem' ? `/ydd_link/add` : `/ydd_link/update`
                , formData
            )
            rander(params)
            layer.close(index)
        },
        btn2: function () {
            const form = layui.form
            form.val('filter', {
                advposname: '',
                advposdesc: '',
                advpossize: '',
            })
            return false
        },
        anim: 5,
        success: async function (layero, index, that) {
            const form = layui.form
            if (btnType !== 'addItem') {
                const info = await axios.get('/ydd_link/rowInfo', { params: { id: btnType } })
                const { data: { data } } = info
                qs('[name="title"]').value = data.title
                qs('[name="url"]').value = data.url
                qs('[name="des"]').value = data.des
                const pos = qsa('[name="type"] option')
                for (let i = 0; i < pos.length; i++) {
                    if (pos[i].value === data.type) {
                        pos[i].selected = true
                        form.render()
                    }
                }
            }
            ///选择框切换事件，根据切换后的值安排表单
            form.on('select(test)', function () {
                const type = qs('[name="type"]')
                qs('#title').style.display = type.value === '1' ? 'flex' : 'none'
                qs('#img').style.display = type.value === '2' ? 'block' : 'none'
            });
            ///显示大图
            qs('.openLp').addEventListener('click', async function () {
                layer.open({
                    type: 1,
                    area: '770px',
                    resize: false,
                    shadeClose: true,
                    title: '图片',
                    content: `<img src="" alt="" class="pic-l">`,
                    success: function () {
                        qs('.pic-l').src = qs('.pic').src
                    }
                })
            })
            ///文件输入框配套
            qs('[name="img"]').addEventListener('change', async function () {
                const upInfo = qs('[name="advimglink"]')
                if (!upInfo.files[0]) return;

                //处理样式
                qs('#upload').style.display = 'none'
                qs('.showPic').style.display = 'flex'
                qs('.last').style.height = '125px'


                ///处理数据发送请求
                let aa = new FormData()
                aa.append('file', upInfo.files[0])
                //发送现有信息
                let data = await axios.post(`/common/upload?type=images`, aa)
                qs('.pic').src = `http://124.223.14.236:8060/${data.data.data.savePath}`
                //自行渲染图片链接
                qs('[name="advimgsrc"]').value = data.data.data.savePath
            })
            form.render()
        }
    })
}
//============================= 渲染分页器 =============================
function randerPage(count, params) {
    layui.use('laypage', function () {
        const laypage = layui.laypage
        laypage.render({
            elem: 'laypage' //注意，这里的 test1 是 ID，不用加 # 号
            , count: count //数据总数，从服务端得到
            , limit: params.limit
            , curr: params.page
            , limits: [2, 3, 5, 10]
            , layout: ['count', 'limit', 'prev', 'page', 'next', 'skip']
            , theme: '#1E9FFF'
            , prev: `<i class="fa fa-angle-left left-nav-li"></i>`
            , next: `<i class="fa fa-angle-right left-nav-li"></i>`
            , jump: function (obj, first) {
                if (!first) {
                    params.page = obj.curr
                    params.limit = obj.limit
                    rander(params)
                }
            }
        });
    })
}
//================================== 行删除/编辑 =============================
qs('body').addEventListener('click', e => {
    const target = e.target
    /* 删除 */
    if (target.className.includes('delItem')) {
        const layer = layui.layer;
        layer.confirm('确认删除？', {
            btn: ['确认', '取消']
            , btn1: async function (index) {
                await axios.get(`/ydd_link/del`, { params: { id: target.dataset.id } })
                rander(params)
                layer.close(index)
            }
        });
    }
    /* 编辑 */
    if (target.className.includes('editItem')) {
        openList1(target.dataset.id)
    }
    if (target.id === 'addItem') {
        openList1('addItem')
    }
    const textLink = qs('#textLink')
    const pictureLink = qs('#pictureLink')
    if (target.id === 'textLink') {
        textLink.className.includes('active') ? '' : textLink.classList.add('active')
        pictureLink.className.includes('active') ? pictureLink.classList.remove('active') : ''
        qs('.blueLine').style.left = textLink.offsetLeft - 8 + 'px'
        params.type = 1

        rander(params)
    }
    if (target.id === 'pictureLink') {
        pictureLink.className.includes('active') ? '' : pictureLink.classList.add('active')
        textLink.className.includes('active') ? textLink.classList.remove('active') : ''
        qs('.blueLine').style.left = pictureLink.offsetLeft - 8 + 'px'
        params.type = 2
        rander(params)
    }
    if (target.id === 'upload') {
        qs('[name="img"]').click()
    }
})
